/**
 * 组织模糊搜索
 * @props   {String}   vlaue     false
 * @props   {Func}     onChange   false
 */
import React from 'react';
 import { TreeSelect } from 'antd';
import { model } from 'utils/model';
/* 常用部门类型枚举（如有误差，以dms为准） */
/* type: 1-大区、2-职能部门、3-事业部、4-市场部、5-车管组 */
const TreeNode = TreeSelect.TreeNode;

@model('commonModel')
class SelectMenu extends React.Component {
  static defaultProps={
    params: {}, // 过滤树
    selectParams: {} // 可选择条件
  };
  constructor(props) {
    super(props);
    const value = props.value || undefined;
    this.state = {
      value: value && value.toString()
    };
    this.handleChange = this.handleChange.bind(this);
    this.triggerChange = this.triggerChange.bind(this);
  }
  componentDidMount() {
    this.props.getDepartment();
  }
  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value || undefined;
      this.setState({ value: value && value.toString() });
    }
  }
  handleChange(value, label, extra) {
    if (!('value' in this.props)) {
      this.setState({ value });
    }
    const extraVal = (extra && extra.triggerNode && extra.triggerNode.props) || {};
    this.triggerChange(value, extraVal);
  }
  triggerChange(changedValue, extraVal) {
    const { onChange, extraChange } = this.props;
    if (onChange) {
      onChange(changedValue);
      extraChange && extraChange(extraVal);
    }
  }
  render() {
    const { placeholder, menuTree = [] } = this.props;
    const loop = data => data.map(item => {
      if (item.childrenList) {
        return <TreeNode key={item.key} title={item.name} value={item.id.toString()}>
          {loop(item.childrenList)}
        </TreeNode>;
      }else{
        return <TreeNode key={item.key} title={item.name} value={item.id.toString()} />;
      }
    });
    const treeSelectProps = {
      ...this.props,
      ...{
        showSearch: true,
        value: this.state.value,
        dropdownStyle: { maxHeight: 400, overflow: 'auto' },
        placeholder: placeholder || '请选择',
        allowClear: true,
        getPopupContainer: () => document.getElementById('mainContainer'),
        treeDefaultExpandAll: true,
        onChange: this.handleChange,
        treeNodeFilterProp: 'title' } };
    return (
      <TreeSelect {...treeSelectProps}>
        {/* <TreeNode key={0} title="根节点" value="0">
          {loop(menuTree)}
        </TreeNode> */}
        {
          loop(menuTree)
        }
      </TreeSelect>
    );
  }
}
export default SelectMenu;
